package com.example.websocket;

import org.tio.core.stat.IpStatListener;
import org.tio.server.ServerTioConfig;
import org.tio.server.TioServer;
import org.tio.server.intf.ServerAioHandler;
import org.tio.server.intf.ServerAioListener;
import org.tio.websocket.server.WsServerStarter;
import org.tio.websocket.server.handler.IWsMsgHandler;

import java.io.IOException;

public class TioWebsocketStarter {

    private WsServerStarter wsServerStarter;

    private ServerTioConfig serverTioConfig;

    private IWsMsgHandler iWsMsgHandler;

    private ServerAioListener serverAioListener;

    private IpStatListener ipStatListener;

    public TioWebsocketStarter(IWsMsgHandler iWsMsgHandler, ServerAioListener serverAioListener, IpStatListener ipStatListener) {
        this.iWsMsgHandler = iWsMsgHandler;
        this.serverAioListener = serverAioListener;
        this.ipStatListener = ipStatListener;
        init();
    }


    private void init() {
        try {
            wsServerStarter = new WsServerStarter(ImConfigConst.SERVER_PORT, iWsMsgHandler);
        } catch (IOException e) {
            e.printStackTrace();
        }
        serverTioConfig = wsServerStarter.getServerTioConfig();
        serverTioConfig.setName(ImConfigConst.PROTOCOL_NAME);
        serverTioConfig.setServerAioListener(serverAioListener);
        serverTioConfig.setIpStatListener(ipStatListener);
        serverTioConfig.ipStats.addDurations(ImConfigConst.IP_STAT_DURATIONS);
        serverTioConfig.setHeartbeatTimeout(ImConfigConst.HEARTBEAT_TIMEOUT);

        //ssl
//        String keyStoreFile = "classpath:ssl/8710433_www.poetize.cn.jks";
//        String trustStoreFile = "classpath:ssl/8710433_www.poetize.cn.jks";
//        String keyStorePwd = "SRxy460Q";
//        serverTioConfig.useSsl(keyStoreFile, trustStoreFile, keyStorePwd);
    }

    public void start() throws Exception {
        wsServerStarter.start();
    }

    public ServerTioConfig getServerTioConfig() {
        return serverTioConfig;
    }

    public IWsMsgHandler getiWsMsgHandler() {
        return iWsMsgHandler;
    }

    public ServerAioListener getServerAioListener() {
        return serverAioListener;
    }

    public IpStatListener getIpStatListener() {
        return ipStatListener;
    }
}
